package com.ms.common.util;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.QrcodeApi;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.ms.common.config.MSBasicConfig;

public class WxUtils {
	/**
	 * 生成单店的二维码存放地址
	 * @param batchId
	 * @param shopId
	 * @return
	 */
	public String getQrFile(String batchId,String shopId){
		String ticket=getQrticket(batchId+"@#"+shopId);
		String fileName="singleShop"+batchId+".jpg";
		if(getQrSaveName(ticket, fileName)){
			return fileName;
		}else{
			return "-1";
		}
		
	}
	/**
	 * 按批次号生成二维码存放地址
	 * @param batchId
	 * @return
	 */
	public String getQrFile(String batchId){
		String ticket=getQrticket(batchId);
		String fileName=batchId+".jpg";
		if(getQrSaveName(ticket, fileName)){
			return fileName;
		}else{
			return "-1";
		}
	}
	
	/**
	 * 获取ticket
	 * @param content
	 */
	public String getQrticket(String content){
		  String str = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+content+"\"}}}";
          ApiResult apiResult = QrcodeApi.create(str);
          String ticket=apiResult.get("ticket");
          return ticket;
	}
	
	/**
	 * 下载二维码
	 * @param ticket
	 * @param fileName
	 * @return
	 */
	public boolean getQrSaveName(String ticket,String fileName){
		boolean flag=true;
	    BufferedInputStream input=  HttpUtils.downloadInputStream("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket);
	       String filePath=MSBasicConfig.qrPath;
	        FileOutputStream os = null;
			try {
				os = new FileOutputStream(filePath+"/"+fileName);
				byte[] buffer = new byte[1024];  
			    int len = -1;  
			    while ((len = input.read(buffer)) != -1) {  
			    	os.write(buffer, 0, len);  
			    }  
				os.close();  
				input.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag=false;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				flag=false;
			}finally{
				try {
					os.close();
					input.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
			} 
			return flag;
		
	}

}
